﻿using System.Reflection;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Context;
using NHibernate.Dialect;
using NHibernate.Driver;
using NHibernate.Mapping.ByCode;
using MSP.Data.NHibernate.Session;
using NHibernate.Tool.hbm2ddl;

namespace MSP.Data.NHibernate
{
	public class NHibernateSessionFactory : INHibernateSessionFactory
	{
		private static ISessionFactory _sessionFactory;

		static NHibernateSessionFactory()
		{
			Configure();
		}

		private static void Configure()
		{
			var mapper = new ModelMapper();
			mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

			HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

			Configuration configure = new Configuration().Configure();
			configure.AddMapping(domainMapping);
			configure.BuildMappings();
			configure.DataBaseIntegration(x =>
				{
                    x.Driver<SqlClientDriver>();
					x.Dialect<MsSql2005Dialect>();
					x.ConnectionStringName = ConnectionString;
				})
			         .CurrentSessionContext<WcfOperationSessionContext>();

            //new SchemaExport(configure).SetOutputFile(@"C:\schema.sql").Execute(true, false, false);

			_sessionFactory = configure.BuildSessionFactory();

		}

		public static string ConnectionString
		{
			get
			{
				return
                    @"Data Source=.; 
                      Initial Catalog=MSP; 
                      User ID=sa; 
                      Password=3186456";
				//ConfigurationManager.ConnectionStrings["MyConnection"].Return(x => x.ConnectionString, "Data Source=myServer;User ID=bckgrd_booklet_app;Password=myPass;");
			}
		}

		public static ISessionFactory SessionFactory
		{
			get
			{
				if (_sessionFactory == null)
					Configure();

				return _sessionFactory;
			}
		}

		public ISession Create()
		{
			//Log.Debug("Creating new session.");
			return SessionFactory.OpenSession();
		}
	}
}